import * as path from "node:path";
import * as fs from "node:fs";
import * as url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const sqlDir = path.join(__dirname, "../sql");
const sqlFiles = fs
  .readdirSync(sqlDir)
  .filter((file) => /^[0-9]{6}\.sql$/.test(file))
  .sort();

/**
 * Turns `str` into a String.raw expression, safely escaping backticks and
 * placeholder strings.
 */
function escape(str) {
  return (
    "String.raw`" +
    str
      .replace(/`/g, '` + "`" + String.raw`')
      .replace(/\$\{/g, "$$` + String.raw`{") +
    "`"
  );
}

const sqlModule =
  "/* This file is auto-generated by `npm run build:sql`; DO NOT EDIT */\n" +
  "// prettier-ignore\n" +
  "export const migrations = {\n" +
  sqlFiles
    .map((file) => {
      const sql = fs.readFileSync(path.join(sqlDir, file), "utf8");
      return `  ${JSON.stringify(file)}: ${escape(sql)},`;
    })
    .join("\n") +
  "\n};\n";

fs.writeFileSync(path.join(__dirname, "../src/generated/sql.ts"), sqlModule);
